<!-- 铭牌仓库 童晓白 2025-07-28 -->
<script setup>
import { NETWORK_CONFIG } from '@/config/network.js'
import { ref, computed } from 'vue';

import { getBadgeNameByAssociation } from '@/utils/skillUtils';
import { useUserStore } from '@/store/user';
import { onLoad } from '@dcloudio/uni-app'

// 获取用户状态管理
const userStore = useUserStore();

// 响应式数据定义
const hangedBadges = ref([]); // 已悬挂的徽章列表
const invisibleBadges = ref([]); // 未悬挂的徽章列表
const allBadges = computed(() => [...hangedBadges.value, ...invisibleBadges.value]); // 合并所有徽章
const loading = ref(false); // 加载状态

// 计算属性：判断徽章是否已悬挂
const isBadgeHanged = (badgeId) => {
  return hangedBadges.value.some(badge => badge.id === badgeId);
};

const contributorId = ref('') // 贡献者ID

// 页面加载时执行
onLoad((options) => {
  // 获取传入的用户ID，如果没有则使用当前用户ID
  contributorId.value = options.uid || userStore.profile.uid
  // 加载徽章数据
  loadBadges(contributorId.value)
})

// 计算属性：判断是否为当前用户
const isCurrentUser = computed(() => {
  // 确保类型一致，都转换为字符串进行比较
  const currentUserId = String(contributorId.value);
  const loginUserId = String(userStore.profile.uid);
  console.log('当前用户ID:', currentUserId, '登录用户ID:', loginUserId);
  return currentUserId === loginUserId;
})



// 加载徽章数据的异步函数
const loadBadges = async (uid) => {
  if (!uid) {
    // 微信小程序端参数验证
    uni.showToast({ 
      title: '参数不完整', 
      icon: 'none',
      duration: 2000 // 微信小程序端添加持续时间
    })
    return
  }
  
  loading.value = true;
  
  // 显示加载提示（微信小程序端优化）
  uni.showLoading({
    title: '加载中...',
    mask: true
  });
  
  try {
    // 获取存储的访问令牌
    const token = uni.getStorageSync('accessToken');
    
    if (isCurrentUser.value) {
      // 当前用户：加载已悬挂徽章
      const hangedRes = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/badge/user-hanged-badges`,
        method: 'GET',
        data: { uid },
        header: { 'Access-Token': `Bearer ${token}` },
        // 微信小程序端添加超时设置
        timeout: 10000
      });
      
      // 微信小程序端响应数据检查
      if (hangedRes.statusCode === 200) {
        console.log('悬挂徽章API响应数据:', hangedRes.data);
        hangedBadges.value = hangedRes.data || [];
        console.log('悬挂徽章数据:', hangedBadges.value);
      } else {
        throw new Error(`悬挂徽章请求失败: ${hangedRes.statusCode}`);
      }
      
      // 当前用户：加载未悬挂徽章
      const invisibleRes = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/badge/top-level-badges`,
        method: 'GET',
        header: { 'Access-Token': `Bearer ${token}` },
        // 微信小程序端添加超时设置
        timeout: 10000
      });
      
      // 微信小程序端响应数据检查
      if (invisibleRes.statusCode === 200) {
        console.log('未悬挂徽章API响应数据:', invisibleRes.data);
        invisibleBadges.value = invisibleRes.data || [];
        console.log('未悬挂徽章数据:', invisibleBadges.value);
      } else {
        throw new Error(`未悬挂徽章请求失败: ${invisibleRes.statusCode}`);
      }
    } else {
      // 其他用户：只加载已悬挂徽章
      const hangedRes = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/badge/user-hanged-badges`,
        method: 'GET',
        data: { uid },
        header: { 'Access-Token': `Bearer ${token}` },
        // 微信小程序端添加超时设置
        timeout: 10000
      });
      
      // 微信小程序端响应数据检查
      if (hangedRes.statusCode === 200) {
        console.log('其他用户悬挂徽章API响应数据:', hangedRes.data);
        hangedBadges.value = hangedRes.data || [];
        console.log('其他用户悬挂徽章数据:', hangedBadges.value);
      } else {
        throw new Error(`悬挂徽章请求失败: ${hangedRes.statusCode}`);
      }
    }
  } catch (error) {
    console.error('加载徽章失败', error);
    // 微信小程序端错误提示优化
    uni.showToast({ 
      title: '加载失败，请重试', 
      icon: 'none',
      duration: 2000
    })
  } finally {
    // 隐藏加载提示
    uni.hideLoading();
    loading.value = false;
  }
};

// 获取徽章标题的函数
const getBadgeTitle = (badge) => {
  // 根据关联代码获取徽章名称
  const badgeName = getBadgeNameByAssociation(badge.association || '000000');
  if (badge.evaluation) {
    return `${badgeName}: ${badge.evaluation}`;
  }
  return badgeName;
};

// 获取用户贡献度的函数（微信小程序端优化）
const getUserContribution = (badge) => {
  // 使用当前页面用户ID，而不是登录用户ID
  const profileUid = Number(contributorId.value);
  
  // 调试信息
  console.log('获取贡献度 - 徽章ID:', badge.id, '用户ID:', profileUid);
  console.log('徽章数据结构:', badge);
  console.log('贡献者列表:', badge.contributors);
  
  // 在贡献者列表中查找当前用户
  const contributor = badge.contributors?.find((c) => c.uid === profileUid);
  const percentage = contributor?.percentage || 0;
  
  console.log('找到的贡献者:', contributor);
  console.log('贡献度百分比:', percentage);
  
  return percentage;
};

// 获取徽章等级样式类的函数
const getBadgeLevelClass = (level) => {
  if (level >= 0 && level <= 9) return 'badge-level level-bronze';
  if (level >= 10 && level <= 19) return 'badge-level level-silver';
  if (level >= 20 && level <= 29) return 'badge-level level-gold';
  if (level >= 30 && level <= 39) return 'badge-level level-platinum';
  if (level >= 40 && level <= 49) return 'badge-level level-diamond';
  if (level >= 50) return 'badge-level level-legendary';
  return 'badge-level level-bronze'; // 默认样式
};

// 获取徽章等级显示文本的函数
const getBadgeLevelText = (level) => {
  if (level >= 0 && level <= 9) return `Lv${level}`;
  if (level >= 10 && level <= 19) return `Lv${level}`;
  if (level >= 20 && level <= 29) return `Lv${level}`;
  if (level >= 30 && level <= 39) return `Lv${level}`;
  if (level >= 40 && level <= 49) return `Lv${level}`;
  if (level >= 50) return `Lv${level}`;
  return `Lv${level}`;
};

// 获取随机徽章图片的函数（微信小程序端适配）
const getRandomBadgeImage = () => {
  // 微信小程序端图片路径调整：使用静态资源路径
  const badgeImages = [
    '/images/badge1.png',
    '/images/badge2.png',
    '/images/badge3.png',
    '/images/badge4.png',
    '/images/badge5.png'
  ];
  const randomIndex = Math.floor(Math.random() * badgeImages.length);
  return badgeImages[randomIndex];
};

// 跳转到协会页面的函数（微信小程序端优化）
const goToAssociation = (badge) => {
  // 使用当前页面用户ID，而不是登录用户ID
  const uid = contributorId.value;
  // 微信小程序端页面跳转
  uni.navigateTo({
    url: `/pages/skill-tree/association/index?contributorId=${uid}&badges=${badge.association}`,
    // 微信小程序端添加失败回调
    fail: (err) => {
      console.error('页面跳转失败', err);
      uni.showToast({ 
        title: '页面跳转失败', 
        icon: 'none',
        duration: 2000
      })
    }
  });
};

// 下拉刷新处理函数（微信小程序端适配）
const onPullDownRefresh = () => {
  // 重新加载徽章数据
  loadBadges(contributorId.value).then(() => {
    // 停止下拉刷新动画
    uni.stopPullDownRefresh();
  }).catch(() => {
    // 出错时也要停止下拉刷新
    uni.stopPullDownRefresh();
  });
};

// 页面显示时刷新数据（微信小程序端适配）
const onShow = () => {
  // 页面显示时重新加载数据
  if (contributorId.value) {
    loadBadges(contributorId.value);
  }
};

// 导出页面生命周期函数
defineExpose({
  onPullDownRefresh,
  onShow
});

// 徽章状态切换功能（微信小程序端适配）
const toggleBadgeStatus = async (badge, newStatus) => {
  if (!isCurrentUser.value) return;
  
  try {
    const token = uni.getStorageSync('accessToken');
    await uni.request({
  url: `${NETWORK_CONFIG.API_BASE_URL}/badge/changestatus?badgeId=${badge.id}&status=${newStatus}`,
  method: 'PATCH',
  header: { 'Access-Token': `Bearer ${token}` },
  timeout: 10000
});
    
    // 更新本地数据
    if (newStatus === 0) {
      // 从悬挂变为隐藏
      hangedBadges.value = hangedBadges.value.filter(b => b.id !== badge.id);
      invisibleBadges.value.push(badge);
    } else {
      // 从隐藏变为悬挂
      invisibleBadges.value = invisibleBadges.value.filter(b => b.id !== badge.id);
      hangedBadges.value.push(badge);
    }
    
    uni.showToast({
      title: newStatus === 1 ? '已悬挂' : '已取消悬挂',
      icon: 'success',
      duration: 2000
    });
  } catch (error) {
    console.error('更新徽章状态失败', error);
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none',
      duration: 2000
    });
  }
};
</script>

<template>
  <view class="badges-page">
    <!-- 加载状态 -->
    <view class="loading-container" v-if="loading">
      <view class="loading-spinner"></view>
      <view class="loading-text">加载中...</view>
    </view>

    <!-- 徽章网格容器 -->
    <view class="badges-container" v-else-if="allBadges.length > 0">
      <view class="badges-grid">
        <view
          class="badge-card"
          v-for="badge in allBadges"
          :key="badge.id"
          @click="goToAssociation(badge)"
        >
          <view class="badge-content">
            <!-- 徽章等级显示 -->
            <view class="badge-header">
              <text :class="getBadgeLevelClass(badge.level)">{{ getBadgeLevelText(badge.level) }}</text>
              <text v-if="isCurrentUser && isBadgeHanged(badge.id)" class="badge-status status-hanged">已悬挂</text>
              <text v-else-if="isCurrentUser" class="badge-status status-hidden">已隐藏</text>
            </view>
            
            <!-- 徽章标题 -->
            <text class="badge-title">{{ getBadgeTitle(badge) }}</text>
            
            <!-- 徽章图片容器 -->
            <view class="badge-image-container">
              <image :src="getRandomBadgeImage()" class="badge-image" mode="aspectFit" />
            </view>
            
            <!-- 贡献度进度条 -->
            <view class="contribution-section">
              <text class="contribution-label">贡献度</text>
              <view class="progress-container">
                <view class="progress-bar" :style="{ width: Math.max(getUserContribution(badge), 2) + '%' }"></view>
                <text class="progress-text">{{ getUserContribution(badge) }}%</text>
              </view>
              <!-- 临时调试信息 -->
              <text class="debug-info" style="font-size: 10px; color: #999;">
                调试: {{ getUserContribution(badge) }}% | 用户ID: {{ contributorId }} | 徽章ID: {{ badge.id }}
              </text>
            </view>
            
            <!-- 徽章操作按钮（仅当前用户可见） -->
            <view v-if="isCurrentUser" class="badge-actions">
              <button 
                v-if="isBadgeHanged(badge.id)" 
                class="badge-action-btn unhang-btn" 
                type="button"
                @click.stop="toggleBadgeStatus(badge, 0)"
              >
                <text class="action-text">取消悬挂</text>
              </button>
              <button 
                v-else 
                class="badge-action-btn hang-btn" 
                type="button"
                @click.stop="toggleBadgeStatus(badge, 1)"
              >
                <text class="action-text">悬挂展示</text>
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态显示 -->
    <view class="empty-state" v-else-if="!loading">
      <text class="empty-icon">🏆</text>
      <text class="empty-title">暂无徽章</text>
      <text class="empty-subtitle">继续努力，获得更多徽章吧！</text>
    </view>
  </view>
</template>

<style scoped>
/* 页面主容器样式 */
.badges-page {
  min-height: 100vh;
  background: #f5f6fa;
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #e0e0e0;
  border-top: 3px solid #4a90e2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.loading-text {
  font-size: 14px;
  color: #7f8c8d;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 徽章容器样式 */
.badges-container {
  padding: 16px;
  /* 为微信小程序原生导航栏留出空间 */
  /* #ifdef MP-WEIXIN */
  padding-top: 8px;
  /* #endif */
}

.badges-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: flex-start; /* 关键：左对齐 */
}

.badge-card {
  box-sizing: border-box;
  width: calc(50% - 6px); /* 6px 是 gap/2，保证两列间距 */
  margin-bottom: 16px;
}

/* 大屏三列 */
@media (min-width: 600px) {
  .badge-card {
    width: calc(33.333% - 8px);
  }
}

/* 超大屏四列 */
@media (min-width: 900px) {
  .badge-card {
    width: calc(25% - 9px);
  }
}

/* 徽章卡片样式 */
.badge-card {
  background: white;
  border-radius: 16px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid rgba(74, 144, 226, 0.1);
  /* 固定卡片高度，确保按钮位置一致 */
  height: 280px;
  display: flex;
  flex-direction: column;
}

.badge-card:active {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
}

.badge-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
  /* 使用 flex 布局，让按钮固定在底部 */
  justify-content: space-between;
  /* 确保内容区域有足够的空间 */
  gap: 8px;
}

/* 徽章头部样式 */
.badge-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 8px;
  /* 固定头部高度 */
  height: 24px;
  /* 确保头部元素垂直居中 */
  gap: 8px;
  /* 确保子元素正确对齐 */
  box-sizing: border-box;
}

/* 徽章等级基础样式 */
.badge-level {
  font-size: 11px;
  font-weight: 700;
  padding: 3px 8px;
  border-radius: 10px;
  /* 添加微妙的边框效果 */
  border: 1px solid rgba(255, 255, 255, 0.2);
  /* 确保文本清晰可见 */
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  /* 确保文本居中对齐 */
  text-align: center;
  /* 确保容器宽度适应内容 */
  display: inline-block;
  /* 防止文本换行 */
  white-space: nowrap;
  /* 确保最小宽度 */
  min-width: fit-content;
}

.level-bronze {
  color: white;
  background: #666666;
  box-shadow: 0 2px 4px rgba(102, 102, 102, 0.3);
}

.level-silver {
  color: white;
  background: #27ae60;
  box-shadow: 0 2px 4px rgba(39, 174, 96, 0.3);
}

.level-gold {
  color: white;
  background: #3498db;
  box-shadow: 0 2px 4px rgba(52, 152, 219, 0.3);
}

.level-platinum {
  color: white;
  background: #9b59b6;
  box-shadow: 0 2px 4px rgba(155, 89, 182, 0.3);
}

.level-diamond {
  color: white;
  background: #f39c12;
  box-shadow: 0 2px 4px rgba(243, 156, 18, 0.3);
}

.level-legendary {
  color: white;
  background: #e74c3c;
  box-shadow: 0 2px 4px rgba(231, 76, 60, 0.3);
}

.badge-status {
  font-size: 11px;
  font-weight: 700;
  color: white;
  background: #4a90e2;
  padding: 3px 8px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(74, 144, 226, 0.3);
  /* 添加微妙的边框效果 */
  border: 1px solid rgba(255, 255, 255, 0.2);
  /* 确保文本清晰可见 */
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.status-hidden {
  color: white;
  background: #f43f5e;
}

/* 徽章标题样式 */
.badge-title {
  font-size: 14px;
  font-weight: 600;
  color: #2c3e50;
  text-align: center;
  line-height: 1.4;
  margin: 0;
  /* 固定标题高度，确保布局一致 */
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 徽章图片容器样式 */
.badge-image-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 8px 0;
  /* 固定图片容器高度 */
  height: 72px;
}

.badge-image {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 贡献度区域样式 */
.contribution-section {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
  /* 固定贡献度区域高度 */
  height: 44px;
}

.contribution-label {
  font-size: 12px;
  color: #64748b;
  font-weight: 600;
  text-align: center;
  letter-spacing: 0.5px;
}

.progress-container {
  width: 100%;
  height: 12px;
  background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
  border-radius: 6px;
  overflow: hidden;
  position: relative;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.progress-bar {
  height: 100%;
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 50%, #a855f7 100%);
  border-radius: 6px;
  transition: width 0.8s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  box-shadow: 0 1px 3px rgba(99, 102, 241, 0.3);
  /* 确保最小宽度，即使为0%也能看到 */
  min-width: 2px;
}

.progress-bar::before {
  /* 移除小程序端不支持的伪元素 */
  display: none;
}

.progress-text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 10px;
  color: white;
  font-weight: 700;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6);
  letter-spacing: 0.5px;
  z-index: 2;
  white-space: nowrap;
  min-width: 24px;
  text-align: center;
}

/* 徽章操作按钮样式 */
.badge-actions {
  width: 100%;
  margin-top: auto;
  /* 确保按钮固定在底部 */
  padding-top: 8px;
}

.badge-action-btn {
  width: 100%;
  padding: 8px 12px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
  font-family: inherit;
}

.badge-action-btn:active {
  transform: scale(0.95);
}

.badge-action-btn.hang-btn {
  background: #4a90e2 !important;
  color: white !important;
}

.badge-action-btn.hang-btn:active {
  background: #34659d !important;
}

.badge-action-btn.unhang-btn {
  background: #f43f5e !important;
  color: white !important;
}

.badge-action-btn.unhang-btn:active {
  background: #aa2c41 !important;
}

.action-icon {
  font-size: 14px;
}

.action-text {
  font-size: 11px;
  white-space: nowrap;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 24px;
  opacity: 0.6;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
}

.empty-subtitle {
  font-size: 14px;
  color: #7f8c8d;
  line-height: 1.5;
}

/* 微信小程序端特定样式 */
/* #ifdef MP-WEIXIN */
.badge-card {
  /* 小程序端卡片优化 */
  margin-bottom: 12px;
  overflow: hidden;
}

.badge-action-btn {
  /* 小程序端按钮样式重置 */
  border: none;
  padding: 8px 12px;
  margin: 0;
  line-height: 1;
}

.badge-action-btn::after {
  border: none;
}

/* 小程序端图片优化 */
.badge-image {
  display: block !important;
  width: 56px !important;
  height: 56px !important;
  border-radius: 12px !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
}

/* 小程序端文本优化 */
.badge-title,
.badge-level,
.contribution-label,
.action-text {
  display: inline-block;
}

/* 小程序端等级标签优化 */
.badge-level {
  text-align: center !important;
  white-space: nowrap !important;
  min-width: fit-content !important;
}

/* 小程序端等级样式优化 */
.level-bronze {
  background: #666666 !important;
  color: white !important;
  box-shadow: 0 2px 4px rgba(102, 102, 102, 0.3) !important;
}

.level-silver {
  background: #27ae60 !important;
  color: white !important;
  box-shadow: 0 2px 4px rgba(39, 174, 96, 0.3) !important;
}

.level-gold {
  background: #3498db !important;
  color: white !important;
  box-shadow: 0 2px 4px rgba(52, 152, 219, 0.3) !important;
}

.level-platinum {
  background: #9b59b6 !important;
  color: white !important;
  box-shadow: 0 2px 4px rgba(155, 89, 182, 0.3) !important;
}

.level-diamond {
  background: #f39c12 !important;
  color: white !important;
  box-shadow: 0 2px 4px rgba(243, 156, 18, 0.3) !important;
}

.level-legendary {
  background: #e74c3c !important;
  color: white !important;
  box-shadow: 0 2px 4px rgba(231, 76, 60, 0.3) !important;
}

/* 小程序端进度条优化 */
.progress-container {
  height: 12px !important;
  background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%) !important;
  border-radius: 6px !important;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.08) !important;
  border: 1px solid rgba(0, 0, 0, 0.05) !important;
}

.progress-bar {
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 50%, #a855f7 100%) !important;
  border-radius: 6px !important;
  transition: width 0.8s cubic-bezier(0.4, 0, 0.2, 1) !important;
  box-shadow: 0 1px 3px rgba(99, 102, 241, 0.3) !important;
  /* 确保最小宽度，即使为0%也能看到 */
  min-width: 2px !important;
}

.progress-text {
  font-size: 10px !important;
  font-weight: 700 !important;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6) !important;
  letter-spacing: 0.5px !important;
  z-index: 2 !important;
}

.contribution-label {
  color: #64748b !important;
  font-weight: 600 !important;
  letter-spacing: 0.5px !important;
}

/* 小程序端调试信息隐藏 */
.debug-info {
  display: none;
}
/* #endif */
</style> 